import { isSpace, isPhone } from '../../utils/validate'
import { Login } from '../../api/user'
import { mapActions } from 'vuex'
export default {
  name: 'Login',
  data() {
    return {
      loading: false,
      phone: null,
      password: null
    }
  },
  computed: {
    //登陆按钮是否不可用
    disLogin: function () {
      return !isPhone(this.phone) || isSpace(this.password)
    }
  },
  methods: {
    ...mapActions(['setLogin']),
    //立即登录
    onLogin() {
      const { phone, password } = this
      if (this.loading) return
      if (!isPhone(phone)) {
        this.$toast('手机号码格式错误')
        return
      } else if (isSpace(password)) {
        this.$toast('请输入密码')
        return
      }
      this.loading = true
      Login({ phone, passWord: password })
        .then(res => {
          this.setLogin(res)
          this.$toast.success('登录成功')
          //如果有重定向
          const { redirect } = this.$route.query
          if (redirect) this.$router.replace(redirect)
          else this.$router.replace({ name: 'Home' })
        })
        .catch(err => {
          this.$dialog.alert({ title: '错误信息', message: err })
        })
        .finally(() => {
          this.loading = false
        })
    }
  }
}
